package com.cj.cms.template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class BuilderHtml {
	protected static Logger logger = LoggerFactory.getLogger(BuilderHtml.class);
    private Configuration config;
    
    public void runBuildContent(String fileName, String templatePath,Map<String,Object> context){
    	BuilderHtmlRunner runner = new BuilderHtmlRunner(fileName,templatePath,context);
    	ThreadExecutorPool.getInstance().getService().execute(runner);
    }
    
	/**
	 * 使用Freemarker生成html格式内容.
	 */
	protected void buildContent(String fileName, String templatePath,Map<String,Object> context){
		try {
			Template template = config.getTemplate(templatePath);
			
            File file = new File(fileName); 
    		if (!file.getParentFile().exists())
    			file.getParentFile().mkdirs();
           
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),config.getDefaultEncoding())); 

            template.process(context, out); 
			
		} catch (IOException e) {
			logger.error("构造模板失败,FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("构造模板失败,FreeMarker处理失败", e);
		}
	}
	
	public class BuilderHtmlRunner implements Runnable {
		private String templatePath;
		private String fileName;
		private Map<String,Object> context;
		public BuilderHtmlRunner(String fileName,String templatePath,Map<String,Object> context){
			this.templatePath = templatePath;
			this.fileName = fileName;
			this.context = context;
		}
		public void run() {
			buildContent(fileName, templatePath, context);
		}
	}
	
	private BuilderHtml() {
		try {
			config = (Configuration)ServletActionContext.getServletContext().getAttribute(FreemarkerManager.CONFIG_SERVLET_CONTEXT_KEY);
		} catch (Exception e) {
			config = new freemarker.template.Configuration();
//			try {
//				config.setDirectoryForTemplateLoading(new File(AppInfo.getAppPath()));
//			} catch (IOException e1) {
//				e.printStackTrace();
//			}
			config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
		}
	}

	private static class Holder {
		public static BuilderHtml instance = new BuilderHtml();
	}

	public static BuilderHtml getInstance() {
		return Holder.instance;
	}
}
